/**
 * Created by keen on 2017/7/22.
 */

package system

import . "kee/plugin"
import (
	"github.com/astaxie/beego"
	"strings"
	"errors"
	"kee/models"
	"strconv"
)

type AppsetController struct {
	BaseController
}

// @Title getStaticBlock
// @Description get all the staticblock by key
// @Param   key     path    string  true        "The email for login"
// @Success 200 {object} models.ZDTCustomer.Customer
// @Failure 400 Invalid email supplied
// @Failure 404 User not found
// @router /staticblock/:key [get]
func (c *AppsetController) Get() {

	c.Data["limit"] = beego.AppConfig.String("limit")
	total, _ := models.GetAllNodeCount()
	limit, _ := strconv.Atoi(beego.AppConfig.String("limit"))
	totalpage := int(total) / limit
	if limit*totalpage < int(total) {
		totalpage ++
	}
	c.Data["total"] = strconv.Itoa(totalpage)

	c.TplName = "system/appset/index.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Css"] = "system/appset/css.html"
	c.LayoutSections["Scripts"] = "system/appset/js.html"
}

func (c *AppsetController) Ok() {
	c.Data["json"] = "abc"
	c.ServeJSON()
}

type AppsetJsonController struct {
	beego.Controller
}

func (c *AppsetJsonController) Get() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllNode(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = l
	}
	c.ServeJSON()

}

type AppsetModalController struct {
	beego.Controller
}

func (c *AppsetModalController) Get() {
	c.TplName = "system/appset/index_modal.html"
}
